package com.example.fz338.ui.me;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.fz338.R;
import com.example.fz338.bean.User;
import com.example.fz338.databinding.FragmentMeBinding;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import cn.bmob.v3.BmobUser;
import de.hdodenhof.circleimageview.CircleImageView;

public class MeFragment extends Fragment {

    private FragmentMeBinding binding;
    private boolean isLogin;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        MeViewModel meViewModel =
                new ViewModelProvider(this).get(MeViewModel.class);

        binding = FragmentMeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        CircleImageView circleImageView = root.findViewById(R.id.circleImageView);
        circleImageView.setOnClickListener(this::click);
        TextView textView = root.findViewById(R.id.textView);
        textView.setOnClickListener(this::click);

        // 这里报错空指针异常并闪退 需要在 AndroidManifest.xml 里的 application 标签增加 android:name=".base.MyApplication" 属性
        // 报错信息: NullPointerException: Attempt to invoke virtual method 'android.content.Context cn.bmob.v3.BmobWrapper.getApplicationContext()' on a null object reference
        // 参考文档: https://doc.bmobapp.com/data/android/#androidmanifestxml
        if (BmobUser.isLogin()) {
            User user = BmobUser.getCurrentUser(User.class);
            textView.setText(user.getUsername());
            isLogin = true;
        } else {
            textView.setText("点击登录");
            isLogin = false;
        }
        LinearLayout linearLayout_map = root.findViewById(R.id.linearLayout_map);
        linearLayout_map.setOnClickListener(v -> Navigation.findNavController(v)
                .navigate(R.id.action_navigation_me_to_mapFragment));
        return root;
    }

    private void click(View view) {
        if(isLogin) {
            Navigation.findNavController(view).navigate(R.id.action_navigation_me_to_infoFragment);
        } else {
            Navigation.findNavController(view).navigate(R.id.action_navigation_me_to_loginFragment);
        }
    }

    // this function is useless
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}